package com.boot.down.service;

import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.websocket.OnClose;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.concurrent.CopyOnWriteArrayList;

/**
 * @author dell
 */
@Component
@ServerEndpoint("/webSocket")
@Slf4j
public class WebSocket {

	private Session session;

	private static CopyOnWriteArrayList<WebSocket> webSocketSet = new CopyOnWriteArrayList<>();

	@OnOpen
	public void onOpen(Session session){
		this.session = session;
		webSocketSet.add(this);
		log.info("打开建立连接信息"+ webSocketSet.size());
	}

	@OnClose
	public void onClose(){
		webSocketSet.remove(this);
		log.info("关闭了相关连接" + webSocketSet.size());
	}

	@OnMessage
	public void onMessage(String message){

		log.info("像前端发送消息" + message);
	}

	public void sendMessage(String message){
		for(WebSocket webSocket : webSocketSet){
			try {
				log.info("广播消息" + message);
				webSocket.session.getBasicRemote().sendText(message);
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}
}
